import { useComponentStore, useStore, useTemporalStore } from "@/store"
import type { questionComponentType } from "@/utils/type"
import { useKeyPress } from "ahooks"
import { nanoid } from "nanoid"




// 判断activeElem是否合法

const isValidActiveElem = () => {
  const activeElem = document.activeElement
  if (activeElem === document.body) return true
  if (activeElem?.matches('div[role="button"]')) return true
  return false
}


const selectNextId = (id: string, list: questionComponentType[]) => {
  const index = list.findIndex(item => item.fe_id === id)
  if (index < 0) {
    return ''
  }
  if (index === list.length - 1) {
    if (list.length != 1)
      return list[index - 1].fe_id
    return ''
  }
  return list[index + 1].fe_id
}



const useBindCanvasKeyPress = () => {
  const {undo} = useTemporalStore.getState()
  const { selectedId,setCopiedComponent,copiedComponent, setSelectedId} = useStore()
  const { addComponent, deleteComponent, componentList } = useComponentStore()


  //删除
  useKeyPress(['Backspace', 'Delete'], () => {
    if (!isValidActiveElem()) return
    deleteComponent(selectedId)
    setSelectedId(selectNextId(selectedId, componentList))
  })
  //复制
  useKeyPress(['ctrl.c'], () => {
    if (!isValidActiveElem()) return
    const item = componentList.find(item => item.fe_id === selectedId)
    if (!item) return
    setCopiedComponent(item)
  })
  //粘贴
  useKeyPress(['ctrl.v'], () => {
    if (!isValidActiveElem()) return
    if (!copiedComponent) return
    addComponent({ ...copiedComponent, fe_id:nanoid()},selectedId)

  })
  //上移键
  useKeyPress('Uparrow', () => {
    if (!isValidActiveElem()) return
    const index = componentList.findIndex(item => item.fe_id === selectedId)
    if (index === 0) return
    setSelectedId(componentList[index - 1].fe_id)

  })
  //下移键
  useKeyPress('Downarrow', () => {
    if (!isValidActiveElem()) return
    const index = componentList.findIndex(item => item.fe_id === selectedId)
    if (index === componentList.length - 1) return
    setSelectedId(componentList[index + 1].fe_id)

  })

  //撤回
  useKeyPress(['ctrl.z'], () => {
    console.log('撤回')
    undo()
  })

}

export default useBindCanvasKeyPress